package com.ctvit.cch.core.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctvit.cch.core.pojo.domain.SocialPlatform;
import com.ctvit.cch.core.service.IHotRecordCollectorService;
import com.ctvit.cch.core.service.ISocialPlatformService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 热榜记录采集任务
 *
 * @author heyingcheng
 * @date 2025/11/15
 */
@Slf4j
@Component("hotRecordCollectorTask")
@ConditionalOnProperty(name = "cch.core.task.hot-record-collector.enabled", havingValue = "true")
public class HotRecordCollectorTask implements SchedulingConfigurer {

    // 每10分钟执行一次
    private static final String CRON_EXPRESSION = "0 0/5 * * * ?";

    @Resource
    private IHotRecordCollectorService hotRecordCollectorService;

    @Resource
    private ISocialPlatformService socialPlatformService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(this::execute, triggerContext -> {
            CronTrigger trigger = new CronTrigger(CRON_EXPRESSION);
            return trigger.nextExecution(triggerContext);
        });
    }

    public void execute() {
        log.debug("执行热榜记录采集任务-开始");

        // 查询所有社交平台的platformCode（只查询状态为0的平台）
        List<SocialPlatform> socialPlatforms = socialPlatformService.list(new LambdaQueryWrapper<SocialPlatform>()
                .select(SocialPlatform::getPlatformCode, SocialPlatform::getPlatformName)
                .eq(SocialPlatform::getStatus, NumberUtils.INTEGER_ZERO.toString()));

        List<String> collectedPlatforms = new ArrayList<>(10);
        // 循环调用collectHotRecords方法采集每个平台的热榜数据
        for (SocialPlatform platform : socialPlatforms) {
            try {
                if (hotRecordCollectorService.collectHotRecords(platform.getPlatformCode())) {
                    collectedPlatforms.add(platform.getPlatformName());
                    log.debug("采集平台[{}]热榜数据成功", platform.getPlatformName());
                } else {
                    log.error("采集平台[{}]热榜数据失败", platform.getPlatformName());
                }
            } catch (Exception e) {
                log.error("采集平台[{}]热榜数据异常", platform.getPlatformName(), e);
            }
        }

        log.debug("执行热榜记录采集任务-结束，共成功采集了[{}]个平台的数据：{}", collectedPlatforms.size(), collectedPlatforms);
    }

}